package com.sctvcloud.pingwu.ui.fragment;

import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.jiongbull.jlog.JLog;

import com.ruihang.generalibrary.ui.dialog.BaseDialogFragment;
import com.ruihang.generalibrary.ui.util.OnItemInternalClick;
import com.ruihang.generalibrary.utils.ListUtils;
import com.ruihang.generalibrary.utils.NetModeUtil;
import com.ruihang.generalibrary.utils.UrlUtils;
import com.sctvcloud.pingwu.R;
import com.sctvcloud.pingwu.application.Cache;
import com.sctvcloud.pingwu.application.Constances;
import com.sctvcloud.pingwu.beans.FChannel;
import com.sctvcloud.pingwu.beans.TvItem;
import com.sctvcloud.pingwu.beans.TvLivingList;
import com.sctvcloud.pingwu.http.AbsNetCallBack;
import com.sctvcloud.pingwu.http.NetUtils;
import com.sctvcloud.pingwu.ui.adapter.TvListAdapter;
import com.sctvcloud.pingwu.ui.adapter.holder.RadioLivingHolder;
import com.sctvcloud.pingwu.ui.dialog.NetModeDiaFragment;
import com.sctvcloud.pingwu.ui.util.RBaseItemDecoration;
import com.sctvcloud.pingwu.ui.utils.GSFPlayerScreenControllImp;
import com.sctvcloud.pingwu.ui.utils.GlideUtil;
import com.sctvcloud.pingwu.ui.utils.SkipUtil;
import com.sctvcloud.pingwu.ui.utils.TVBottomControllerImp;
import com.sctvcloud.pingwu.ui.utils.TVTopControllerImp;
import com.sctvcloud.pingwu.ui.widget.BasePlayerView;
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.sctvcloud.pingwu.ui.dialog.NetModeDiaFragment.NO_TAG;
import static com.sctvcloud.pingwu.ui.dialog.NetModeDiaFragment.OK_TAG;


public class RadioNewFragment extends ColumnBaseFragment implements CanRefreshLayout.OnRefreshListener, RadioLivingHolder.OnItemClickListener {
    @BindView(R.id.video_player)
    protected BasePlayerView videoPlayer;
    //    @BindView(R.id.view_pager)
//    protected ViewPager viewPager;
    @BindView(R.id.fragment_tv_img_play)
    protected ImageView play;
    @BindView(R.id.tv_living_refresh)
    protected CanRefreshLayout refreshLayout;
    @BindView(R.id.can_content_view)
    protected RecyclerView living_list;


    private TvListAdapter livingAdapter;
    private LinearLayoutManager manager;
    private boolean mIsLoading = false;
    private Handler handler;
    private List<FChannel> fPrograms = new ArrayList<>();
    private FChannel currentChannel;
    private TvFragment parentFragment;

    private List<TvItem> dataList = new ArrayList<>();
    private TvLivingList tvLivingList;
    private String mVideoUrl;
    /**
     * 卫视直播的url
     */
    private String liveUrl;

    private String liveImgUrl;

    private boolean isPortrait = true;

    private TVTopControllerImp topController;
    private GSFPlayerScreenControllImp screenController;
    private TVBottomControllerImp bottomControllerImp;
    private NetModeDiaFragment netDiaFragment;
    private String titleTemp;

    /**
     * 直播的标题缓存
     */
    private String liveTitleTemp;

    private boolean isPlayingWhenPause;

    private boolean isFirst = true;//是否第一次播放

    //    private OrientationUtils orientationUtils2;
    private int currentItem = 0;
    private FChannel livingChannel;
    private boolean isRadio;
    private boolean isParentFragmentShow = true;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_tv_new, container, false);
        ButterKnife.bind(this, view);

        return view;
    }

    protected void initViews(View v, @Nullable Bundle savedInstanceState) {
//        group.setOnCheckedChangeListener(this);
        handler = new Handler();
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setLoadMoreEnabled(false);
        manager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        living_list.setItemAnimator(new DefaultItemAnimator());
        living_list.addItemDecoration(new RBaseItemDecoration(2));
        living_list.setLayoutManager(manager);
        getTvData();
    }

    @Override
    public void onRefresh() {
        if (mIsLoading) {
            return;
        }
        mIsLoading = true;

    }

    /**
     * 获取频道相关数据
     */
    private void getTvData() {
        if (isRequesting) {
            return;
        }
//        channelUrl = "http://kscgc.sctv.com/sctv/tv/index/tv.json";
        if (TextUtils.isEmpty(channelUrl)) {
            toast(R.string.data_wrong);
            return;
        }
        isRequesting = true;
        NetUtils.getNetAdapter().getTvLivingList(getOwnerName(), channelUrl, new AbsNetCallBack<TvLivingList>(TvLivingList.class) {
            @Override
            public void onSuc(TvLivingList tv) {
                JLog.e("getTvData=onSuconSuconSuc");
                if (tv != null) {
                    tvLivingList = tv;
                    initTvData(tv.getAudioChannel());
                }
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                super.onError(ex, errorMsg);
            }

            @Override
            public void onEnd() {
                super.onEnd();
                isRequesting = false;
            }
        });

    }

    private void initTvData(List<FChannel> list) {
        if (ListUtils.isListValued(list)) {
            this.fPrograms.addAll(list);
            if (livingAdapter == null) {
                livingAdapter = new TvListAdapter(getActivity(), fPrograms,this).setItemInternalClick(livingOnItemClick);
                livingAdapter.setSelectPos(0);
                living_list.setAdapter(livingAdapter);
                setPlayMedia(fPrograms.get(0), true);
            } else {
                livingAdapter.setData(fPrograms);
                if (livingAdapter.getSelectPos() >= 0) {
                    livingAdapter.setSelectPos(livingAdapter.getSelectPos());
                    setPlayMedia(fPrograms.get(livingAdapter.getSelectPos()), true);
                } else {
                    livingAdapter.setSelectPos(0);
                    setPlayMedia(fPrograms.get(0), true);
                }
                livingAdapter.notifyDataSetChanged();
            }


        }
    }

    private OnItemInternalClick livingOnItemClick = new OnItemInternalClick() {
        @Override
        public void onItemInternalClick(View itemView, View view, int position) {
            FChannel fProgram = fPrograms.get(position);
            if (null != fProgram) {
                setPlayMedia(fProgram, true);
                livingAdapter.setSelectPos(position);
                livingAdapter.notifyDataSetChanged();

            }
        }
    };
    private RadioLivingHolder lastViewHolder;
    private int lastIndex = -1;

    @Override
    public void OnItemClick(RadioLivingHolder viewHolder, int position) {
        if (lastIndex != position) {
            if (null == lastViewHolder) {
                RecyclerView.LayoutManager manager = living_list.getLayoutManager();
                View lastView = manager.findViewByPosition(lastIndex);
                if (null != lastView && living_list.getChildViewHolder(lastView) instanceof RadioLivingHolder) {
                    lastViewHolder = (RadioLivingHolder) living_list.getChildViewHolder(lastView);
                    lastViewHolder.resetUnSelected();
                }
            }
            if(null!=lastViewHolder){
                lastViewHolder.resetUnSelected();
            }
            viewHolder.showSelected();
            lastIndex = position;
            lastViewHolder = viewHolder;
        }
    }



    /**
     * 从Parent fragment判断是否显示的当前页
     *
     * @return
     */
    private boolean isThisPageShowing() {
        ColumnBaseFragment fragment = ((HomeFragment) getParentFragment()).getCurrentFragment();
        if (fragment instanceof TvFragment && isParentFragmentShow) {
            return true;
        }
        return false;
    }

    @Override
    public void onResume() {
        super.onResume();
        if (videoPlayer != null) {
            videoPlayer.setMute(videoPlayer.isMute());
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            isParentFragmentShow = true;
//            videoPlayer.onResume();
        } else {
            isParentFragmentShow = false;
            videoPlayer.onVideoPause();
        }
    }

    public void parentTitleClick() {
        if (videoPlayer != null) {
            //暂停播放
            if (videoPlayer.getCurrentState() == BasePlayerView.CURRENT_STATE_PLAYING) {
                isPlayingWhenPause = true;
            }
            videoPlayer.onVideoPause();
            videoPlayer.setOrientationChangeEnable(false);
            //暂停播放时，停止统计在线数据
            sendId = "";
            sendType = 0;
        }
    }

    @Override
    protected boolean onFragmentShow(boolean isFirst, boolean isCallFromResume) {
        isFront = true;
        if (tvLivingList == null || !ListUtils.isListValued(tvLivingList.getAudioChannel() ) ) {
            //如果有一条数据为无效数据，则重新获取
            getTvData();
        }else{

        }
        return super.onFragmentShow(isFirst, isCallFromResume);
    }

    @Override
    protected void onFragmentUnShowed(boolean isCallFromPause) {
        super.onFragmentUnShowed(isCallFromPause);
        //首页频道fragment页面切换离开
//        JLog.e("ddac  cal from pause  " + isCallFromPause + "  floatutil=" + floatVideoUtils);
        isFront = false;
        if (videoPlayer != null) {
            if (videoPlayer.isPlaying()) {
                JLog.e("ddac   will to pause");
                isPlayingWhenPause = true;
                videoPlayer.onVideoPause();
            }
        }
        if (videoPlayer != null && pauseType != 1) {
            //暂停播放
            if (videoPlayer.getCurrentState() == BasePlayerView.CURRENT_STATE_PLAYING) {
                isPlayingWhenPause = true;
            }
            videoPlayer.onVideoPause();
            videoPlayer.setOrientationChangeEnable(false);
            //暂停播放时，停止统计在线数据
            sendId = "";
            sendType = 0;

        }
        pauseType = 0;
    }

    private boolean isRequesting = false;

    @Override
    public boolean hasShowPlayer() {
        return videoPlayer != null && videoPlayer.getVisibility() == View.VISIBLE;
    }

    @Override
    public void onDestroyView() {

        if (floatVideoUtils != null) {
            floatVideoUtils.onDestory();
        }
        if (null != RHTask) {
            RHTask.cancel();
            RHTask = null;
        }
        if (null != readyOnlineTimer) {
            readyOnlineTimer.cancel();
            readyOnlineTimer.purge();
            readyOnlineTimer = null;
        }
        super.onDestroyView();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);

    }

    @OnClick(value = {R.id.fragment_tv_img_play})
    public void click(View view) {
        if (TextUtils.isEmpty(mVideoUrl)) {
            toast("数据错误");
            return;
        }
//        playVideo();
    }


    public String getChannelUrl() {
        return channelUrl;
    }

    private boolean setVideoPlayer(String videoUrl, boolean isLiving, boolean isRadio) {
        this.isRadio = isRadio;
        mVideoUrl = videoUrl;
        // if (NetUtils.isWifiConnected(getContext())) {
        if (null != livingChannel && isLiving) {
            sendId = livingChannel.getChannelId();
            int resourceType = 0;
            if (isRadio) {
                sendType = 3;
                resourceType = 6;
            } else {
                resourceType = 5;
                sendType = 2;
            }
            if (!lastSendId.equalsIgnoreCase(sendId)) {
                lastSendId = sendId;
                SkipUtil.skipToAddUserOperate(getContext(), getOwnerName(), resourceType, 0, "频道/广播 播放", sendId, Cache.getInstance().getCurrentChannelId());
            }
        } else {
            sendId = "";
            sendType = 0;
        }
        playVideo(isLiving, isRadio);
        return true;

    }

    private void playVideo(boolean isLiving, boolean isRadio) {
        int netType = NetModeUtil.GetNetype(getContext());
        boolean haseCallstop = false;
        if (getContext() == null) {
            return;
        }

        videoPlayer.setLiving(isLiving);
        videoPlayer.setRadio(isRadio);
        videoPlayer.setThumbPlay(isRadio);
        if (isFirst) {
            videoPlayer.setMute(false);
//            AudioManager mAudioManager = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
//            mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 0, 1);
//          int  max = mAudioManager.getStreamMaxVolume( AudioManager.STREAM_MUSIC );
//            int current = mAudioManager.getStreamVolume( AudioManager.STREAM_MUSIC );
//            JLog.e("AudioManager","---max = "+max+" current = "+current);
        }

        if (isLiving && videoPlayer.getThumbImge() != null) {
            GlideUtil.getGlideWithLarge169DefNotFit(getContext(), liveImgUrl).into(videoPlayer.getThumbImge());
        }
        videoPlayer.setUp(mVideoUrl, false, titleTemp);
        if (netType == 1) {
            if (isFront) {
                videoPlayer.startPlay();
            }
        }
        isFirst = false;

    }

    private void showNetProt() {
        if (Cache.getInstance().isCheckNet()) {
            videoPlayer.startPlayLogic();
            return;
        }
        if (netDiaFragment == null) {
            netDiaFragment = new NetModeDiaFragment();
        }
        if (!netDiaFragment.isAdded()) {
            netDiaFragment.setCallBack(netBack);
            netDiaFragment.show(getChildFragmentManager(), NET_TAG);
        }
    }

    protected int getCurrentScrollY() {
        return 0;
    }

    protected void onChangedToPortrait(Configuration newConfig) {
    }

    protected void onChangedToLandscape(Configuration newConfig) {
        if (videoPlayer != null) {
//            JLog.e("GSYVideoPlayer  " + videoPlayer.getFullWindowPlayer() + "\n " + videoPlayer);
//            JLog.e("rrsr  " + videoPlayer.getFullWindowPlayer() + "\n " + videoPlayer + "   " + orientationUtils.isClickLand());
        }
    }

    private int pauseType = 0;//-1 非收音机   1为收音机

    @Override
    public void onPause() {
        if (!isRadio) {
            if (videoPlayer != null) {
                videoPlayer.onVideoPause();
            }
            pauseType = -1;
        } else {
            pauseType = 1;
        }
        super.onPause();
//        isFront = false;
    }

    @Override
    public boolean onBackPressed() {
        if (StandardGSYVideoPlayer.backFromWindowFull(getContext())) {
            actionToPortrait();
            return true;
        }
        return super.onBackPressed();
    }

    @Override
    public void onDestroy() {

        super.onDestroy();
    }


    /**
     * 确定使用移动网络播放的回调，开始播放
     */
    BaseDialogFragment.ICallBack netBack = new BaseDialogFragment.ICallBack() {
        @Override
        public void onCallBackMsg(BaseDialogFragment fragment, Message msg) {
            if (msg.what == NO_TAG) {
//                floatVideoUtils.stopVideoView();
            } else if (msg.what == OK_TAG) {
//                floatVideoUtils.setLiving(false).play(img, mVideoUrl);
//                if (topController != null) {
//                    topController.setTitle(titleTemp);
//                }
                Cache.getInstance().setCheckNet(true);
                videoPlayer.startPlayLogic();
            }
        }
    };


    private void getTvLivingData(FChannel fchannel, boolean isRadio) {
        if (!TextUtils.isEmpty(fchannel.getLiveUrl())) {
            liveUrl = fchannel.getLiveUrl();
            livingChannel = fchannel;
        }
        if (!TextUtils.isEmpty(fchannel.getChannelName())) {
            titleTemp = fchannel.getChannelName();
            liveTitleTemp = fchannel.getChannelName();
        }
        liveImgUrl = fchannel.getDataImg();
        if (topController != null) {
            topController.setTitle(titleTemp);
        }
        //TODO 启动直播在线统计
        startOnlineService(handlerOnline);
        setVideoPlayer(liveUrl, true, isRadio);
    }


    public void setPlayMedia(FChannel channel, boolean isRadio) {
        if (channel == null) {
            toast("无效播放地址");
            return;
        }

        livingChannel = channel;
        this.isRadio = isRadio;
        String title = channel.getChannelName();
//        tv_title.setText(title);
        if (!TextUtils.isEmpty(channel.getLiveUrl())) {
            mVideoUrl = UrlUtils.linkUrls(Constances.ST_BASE_URL, channel.getLiveUrl());
            titleTemp = channel.getChannelName();
//            playVideo();
            if (setVideoPlayer(mVideoUrl, true, isRadio)) {
                int netType = NetModeUtil.GetNetype(getContext());
                if (videoPlayer.getThumbImge() != null) {
                    GlideUtil.getGlideWithLarge169DefNotFit(getContext(), channel.getChannelImage()).into(videoPlayer.getThumbImge());
                }
//                JLog.e("bbab  net type=" + netType + "  img=" + fProgram.getProgrammeImage());
                if (netType == 1 && isFront) {
                    if (videoPlayer != null) {
                        videoPlayer.setMute(videoPlayer.isMute());
                        videoPlayer.setLiving(true);
                        videoPlayer.setRadio(isRadio);
                        videoPlayer.startPlay();
                    }
                }
            }
        } else {
            toast("播放地址为空");
        }


    }

    private boolean isInitListener = false;

    /**************************直播在线日志统计******************************/


    Handler handlerOnline = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg != null && msg.what == 22) {
                sendOnlineMsg();
            }
        }
    };
    private Timer readyOnlineTimer;
    private TimerTask RHTask;
    private String sendId = "";
    private String lastSendId = "";
    private int sendType = 0;

    /**
     * 启动直播统计心跳
     *
     * @param mHandler
     */
    public void startOnlineService(final Handler mHandler) {
        long HeartbeatTime = 60 * 1000;//心跳时间
        if (null == readyOnlineTimer) {
            try {
                readyOnlineTimer = new Timer(true);
                java.util.Date d1 = new java.util.Date();
                if (null == RHTask) {
                    RHTask = new TimerTask() {
                        @Override
                        public void run() {
                            Message msg = new Message();
                            msg.what = 22;
                            mHandler.sendMessage(msg);
                        }
                    };
                }
                readyOnlineTimer.schedule(RHTask, d1, HeartbeatTime);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 向服务器发送日志
     */
    private void sendOnlineMsg() {
        if (!TextUtils.isEmpty(sendId)) {
            SkipUtil.skipToAddOnline(getContext(), getOwnerName(), sendId, sendType);
        }
    }


}
